package com.action.pc.user;

import com.bean.Merchant;
import com.bean.Sys_user;
import com.common.BaseAction;
import com.common.ModelAndJson;
import com.github.pagehelper.Page;
import com.service.city.CityService;
import com.service.merchant.MerchantService;
import com.service.user.JsService;
import com.service.user.UserService;
import com.util.DESUtils;
import com.util.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * Created by lvjianqing on 2017/9/9.
 */
@Controller
@RequestMapping("user")
public class UserAction extends BaseAction {
    Logger log = Logger.getLogger(UserAction.class);
    @Autowired
    private UserService userService;
    @Autowired
    private CityService cityService;
    @Autowired
    private JsService jsService;
    @Autowired
    private MerchantService merchantService;

    /**
     * 用户列表
     */
    @RequestMapping("list")
    public ModelAndView list(HttpServletRequest request, ModelMap modelMap, UserVo vo) {
        int pageNum = vo.getPageNumInt();
        int pageSize = vo.getPageSizeInt();
        HashMap<String, Object> paraMap = new HashMap<>();
        filterParaMap(paraMap);
        if (StringUtil.isNotEmpty(vo.getLoginName())) {
            paraMap.put("loginName", vo.getLoginName());
        }
        if (StringUtil.isNotEmpty(vo.getTel())) {
            paraMap.put("tel", vo.getTel());
        }
        if (StringUtil.isNotEmpty(vo.getRealName())) {
            paraMap.put("realName", vo.getRealName());
        }
        Page page = userService.findByPage(pageNum, pageSize, paraMap);
        modelMap.put("page", page);
        modelMap.put("pages", page.getPages());
        modelMap.put("pageNum", page.getPageNum());
        modelMap.put("pageSize", page.getPageSize());
        modelMap.put("vo", vo);
        return new ModelAndView("/pc/user_list", modelMap);
    }

    @RequestMapping("modify")
    public ModelAndView modify(HttpServletRequest request, ModelMap modelMap, UserVo vo) {
        Integer id = vo.getId();
        Sys_user user = new Sys_user();
        if (id != null) {
            user = userService.findUserById(id);
            if (user != null) {
                List<Long> ids = jsService.findJsIdByYhId(user.getId());
                if (ids != null && ids.size() > 0) {
                    Long jsid = ids.get(0);
                    modelMap.put("jsid", jsid);
                }
                HashMap<String, Object> map = new HashMap<>();
                map.put("cityid", user.getCityid());
                Page p = merchantService.findByPage(1, 0, map);
                if (p != null && p.getResult() != null) {
                    List list = p.getResult();
                    modelMap.put("merchant_list", list);
                }
            }
        }
        modelMap.put("user", user);
        modelMap.put("myjsid", getJsid());
        return new ModelAndView("/pc/user_modify", modelMap);
    }

    @RequestMapping("save")
    public ModelAndView save(HttpServletRequest request, ModelMap modelMap, UserVo vo) {
        Sys_user user = new Sys_user();
        user.setId(vo.getId());
        user.setTel(vo.getTel());
        user.setRealname(vo.getRealName());
        user.setLoginname(vo.getLoginName());
        user.setCityid(vo.getCityId());
        user.setMerchantid(vo.getMerchantid());
        userService.saveUser(user);
        Long jsid = getJsid();
        if(jsid==2){
            if (user.getId() != null && vo.getJsid() != null) {
                jsService.saveYhjs(user.getId(), new Long[]{vo.getJsid()});
            }
        }else if(jsid==3){
            jsService.saveYhjs(user.getId(), new Long[]{4L});
        }

        return new ModelAndView("redirect:/user/list.htm", modelMap);
    }

    @RequestMapping("checkloginname")
    @ResponseBody
    public boolean checkloginname(UserVo vo) {
        String loginName = vo.getLoginName();
        if (StringUtil.isEmpty(loginName)) {
            return false;
        }
        Sys_user user = userService.getUserByLoginName(loginName);
        if (user != null) {//存在
            return false;
        }
        return true;
    }

    @RequestMapping("del")
    @ResponseBody
    public String jsDel(HttpServletRequest request, ModelAndJson modelMap, UserVo vo) {
        Integer id = vo.getId();
        if (id != null) {
            userService.delUser(id);
        }
        modelMap.setTrue("删除成功");
        return modelMap.toString();
    }

    @RequestMapping("resetpassword")
    @ResponseBody
    public String resetPassword(HttpServletRequest request, ModelAndJson modelMap, UserVo vo) {
        Integer id = vo.getId();
        if (id != null) {
            Sys_user user = userService.findUserById(id);
            if (user == null) {
                return "重置失败";
            } else {
                try {
                    user.setPassword(DESUtils.encrypt("123456"));
                    userService.saveUser(user);
                    return "重置成功";
                } catch (Exception e) {
                    return "重置失败";
                }
            }
        } else {
            return "重置失败";
        }
    }

    @RequestMapping("tochangepw")
    public ModelAndView tochangepw(HttpServletRequest request, ModelMap modelMap, UserVo vo) {
        return new ModelAndView("/pc/user_password_change", modelMap);
    }

    @RequestMapping("changepassword")
    @ResponseBody
    public String changePassword(HttpServletRequest request, ModelAndJson modelMap, UserVo vo) {
        String mm = vo.getPassword();
        String xmm = vo.getNewpassword();
        Sys_user user = getSysUser();
        if (StringUtil.isEmpty(mm) || StringUtil.isEmpty(xmm)) {
            modelMap.setFalse("-1", "密码为空");
        } else {
            try {
                if (!user.getPassword().equals(DESUtils.encrypt(mm))) {
                    modelMap.setFalse("-2", "密码错误");
                } else {
                    user.setPassword(DESUtils.encrypt(xmm));
                    userService.saveUser(user);
                    modelMap.setTrue("修改成功");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return modelMap.toString();
    }

    @RequestMapping("merchants")
    @ResponseBody
    public String merchants(HttpServletRequest request, ModelAndJson modelMap, UserVo vo) {
        Integer cityid = vo.getCityId();
        if (cityid != null) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("cityid", cityid);
            Page p = merchantService.findByPage(1, 0, map);
            if (p != null && p.getResult() != null) {
                List<Merchant> list = p.getResult();
                StringBuffer sb = new StringBuffer();
                sb.append("<option value=''>请选择</option>");
                if (list != null && list.size() > 0) {
                    for (Merchant m : list) {
                        sb.append("<option value='").append(m.getId()).append("'>").
                                append(m.getMtname()).append(" (").append(m.getProvincename()).append(m.getCityname()).append(m.getRegionname())
                                .append(")</option>");
                    }
                }
                modelMap.put("merchants", sb.toString());
            }
        }
        return modelMap.toString();
    }
}
